<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>配置管理</el-breadcrumb-item>
      <el-breadcrumb-item>七益活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form :inline="true" class="toolbar">
        <el-form-item>
          <el-button @click="addRoot" type="success" style="padding:8px 10px; font-size: 12px;">添加活动</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        highlight-current-row
        v-loading="gridLoading"
        class="grid"
        style="width: 100%；"
      >
        <el-table-column label="活动标题" prop="title"></el-table-column>
        <!-- <el-table-column label="活动内容" prop="content" >
        </el-table-column>-->
        <el-table-column label="用户支付" prop="price"></el-table-column>
        <el-table-column label="实际消费" prop="inPrice"></el-table-column>
        <el-table-column label="列表图片" prop="img">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px;"
              :src="scope.row.img"
              :preview-src-list="srcList"
              @click="checkimg(scope.row.img)"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="轮播图" prop="bannerImg">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px;"
              :src="getimgtu(scope.row.bannerImg)[0]"
              :preview-src-list="getimgtu(scope.row.bannerImg)"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="活动总次数" prop="totalNumber"></el-table-column>
        <el-table-column label="使用次数" prop="curNumber"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status == 1 ? 'success':'danger'"
            >{{scope.row.status == 1 ? '开启' : '关闭'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="goEdit(scope)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="添加活动" :visible.sync="addDialogVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-position="left" label-width="100px" ref="addForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="所属类别" prop="title">
          <el-select v-model="addForm.category" placeholder="请选择" clearable>
            <el-option
              v-for="(item,index) in isshiMIng"
              :label="item.name"
              :key="index"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付价格" prop="price">
          <el-input v-model="addForm.price" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="消费价格" prop="inPrice">
          <el-input v-model="addForm.inPrice" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="每人返还价格" prop="everyRePrice">
          <el-input v-model="addForm.everyRePrice" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="活动总次数" prop="totalNumber">
          <el-input v-model="addForm.totalNumber" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="使用次数" prop="curNumber">
          <el-input v-model="addForm.curNumber" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="多少次产生一个七益" prop="number">
          <el-input v-model="addForm.number" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="规则" prop="remark">
          <el-input type="textarea" v-model="addForm.remark"></el-input>
        </el-form-item>

        <el-form-item label="列表图片">
          <el-upload
            style="display:flex;align-item:center; flex-direction: column;margin-top:1rem;"
            class="upload-demo"
            :data="params"
            :action="form.Url"
            :headers="dTuploadHeader"
            :on-preview="dThandlePreview"
            :on-remove="dThandleRemove"
            :before-upload="dTbeforeUpload"
            :on-success="dTuploadSuccess"
            list-type="picture"
            :limit="1"
          >
            <!-- list-type="picture"-->
            <el-button size="small" type="primary">点击上传商品主图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图图片">
          <el-upload
            style="display:flex;align-item:center;flex-direction: column;margin-top:1rem;"
            class="upload-demo"
            :data="params"
            :action="form.Url"
            :headers="uploadHeader"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :multiple="true"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            list-type="picture"
          >
            <!-- list-type="picture"-->
            <el-button size="small" type="primary">点击上传轮播图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <squill-editor-qiniu
            :token="form.token"
            v-model="addForm.content"
            :domain="form.domain"
            :uploadUrl="form.Url"
            ref="squill"
          ></squill-editor-qiniu>
          <!-- <quill-editor v-model="addForm.content" ref="myQuillEditor"></quill-editor> -->
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="addForm.status" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormSubmit" :loading="addFormLoading">提 交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改活动" :visible.sync="editDialogVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-position="left" label-width="100px" ref="addForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="所属类别" prop="title">
          <el-select v-model="editCategory" @change="editSelectChange" placeholder="请选择" clearable>
            <el-option
              v-for="(item,index) in isshiMIng"
              :label="item.name"
              :key="index"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付价格" prop="price">
          <el-input v-model="editForm.price" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="消费价格" prop="inPrice">
          <el-input v-model="editForm.inPrice" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="每人返还价格" prop="everyRePrice">
          <el-input v-model="editForm.everyRePrice" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="活动总次数" prop="totalNumber">
          <el-input v-model="editForm.totalNumber" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <!-- <el-form-item label="使用次数" prop="curNumber">
          <el-input v-model="editForm.curNumber" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item> -->
        <el-form-item label="多少次产生一个七益" prop="number">
          <el-input v-model="editForm.number" auto-complete="off" :maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="规则" prop="remark">
          <el-input type="textarea" v-model="editForm.remark"></el-input>
        </el-form-item>

        <el-form-item label="列表图片">
          <el-upload
            style="display:flex;align-item:center; flex-direction: column;margin-top:1rem;"
            class="upload-demo"
            :data="params"
            :action="form.Url"
            :headers="dTuploadHeader"
         
            :on-remove="edithandleRemove"
            :before-upload="beforeUpload"
            :on-success="edituploadSuccess"
            list-type="picture"
            :limit="1"
            :file-list="fileList1"
          >
            <!-- list-type="picture"-->
            <el-button size="small" type="primary">点击上传商品主图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="轮播图图片">
          <el-upload
            style="display:flex;align-item:center;flex-direction: column;margin-top:1rem;"
            class="upload-demo"
            :data="params"
            :action="form.Url"
            :headers="uploadHeader"
     
            :on-remove="editDthandleRemove"
            :multiple="true"
            :before-upload="beforeUpload"
            :on-success="editDtuploadSuccess"
            list-type="picture"
            :file-list="fileList2"
          >
            <!-- list-type="picture"-->
            <el-button size="small" type="primary">点击上传轮播图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <squill-editor-qiniu
            :token="form.token"
            v-model="editForm.content"
            :domain="form.domain"
            :uploadUrl="form.Url"
            ref="squill"
          ></squill-editor-qiniu>
          <!-- <quill-editor v-model="addForm.content" ref="myQuillEditor"></quill-editor> -->
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="editBtn" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDataInfo" :loading="editFormLoading">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SquillEditorQiniu from "@/components/quill-editor/quill-editor";
export default {
  data() {
    return {
      // 上传图片时候，要传递的请求头
      uploadHeader: {
        // 需要手动指定一个 Authorization
        Authorization: ""
      },
      isshiMIng: [
        {name:'手机卡',id:1},
        {name:'油卡',id:2}
      ],
      dataList: [],
      srcList: [],
      addDialogVisible: false,
      addForm: {
        id: 0,
        title: "",
        category: "",
        price: "",
        inPrice: "",
        picUrl: "",
        piclist: [],
        content: "",
        remark: "",
        everyRePrice: "",
        number: "",
        curNumber: "",
        totalNumber: "",
        status: false
      },
      editForm: {},
      imageUrl: "",
      form: {
        token: "", //七牛token
        Url: "", //获取上传路径
        domain: "" //上传路径 二级
      },
      params: {
        token: "",
        key: ""
      },
      editDialogVisible: false,
      editImgList:[],
      editFormLoading:false,
      editCategory:'',
      editBtn:null
    };
  },
  created() {
    this.getsevenList();
    this.getQnToken();
    //this.getSevenType();
  },
  components: {
    SquillEditorQiniu
  },
  methods: {
    editSelectChange(e){
      console.log(e);
      this.editForm.category=e;
    },
    goEdit(data) {
      console.log(data.row);
      this.editForm = data.row;
      this.editDialogVisible = true;
      if(data.row.category==1){
        this.editCategory='手机卡'
      }else if(data.row.category==2){
        this.editCategory='油卡'
      }
      if(data.row.status==1){
        this.editBtn=true;
      }else{
        this.editBtn=false;
      }
      this.fileList1 = [
        {
          name: "image.png",
          url: data.row.img
        }
      ];
      let picDataList = JSON.parse(data.row.bannerImg);
      this.editImgList=JSON.parse(data.row.bannerImg);
      let picOneData = [];
      picDataList.forEach((item, i) => {
        console.log(item);
        let obj = {
          name: "image" + i,
          url: item.bannerimg
        };
        picOneData.push(obj);
      });
      this.fileList2 = picOneData;
    },
    editDataInfo(){
      this.editForm.bannerImg=JSON.stringify(this.editImgList);
      if(this.editBtn){
        this.editForm.status =1;
      }else{
        this.editForm.status =0;
      }

      console.log(this.editForm);
      this.$http.post("/manage/seven/addEdit", this.editForm).then(res => {
        if (res.data.status == 1) {
          this.editDialogVisible = false;
          this.getsevenList();
          this.$message({
            message: "修改成功",
            type: "success"
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    //   POST
    getSevenType() {
      this.$http.post("/manage/seven/getSevenType", {}).then(res => {
        console.log(res)
        if (res.data.status == 1) {
          this.isshiMIng = res.data.data;
        } else {
        }
      });
    },
    async getQnToken() {
      const { data: res } = await this.$http.post(
        "/manage/userFile/qiNiuUpload",
        {}
      );
      console.log(res);
      this.form.token = res.data.token;
      this.params.token = res.data.token;
      this.form.domain = res.data.domain;
      this.form.Url = res.data.upload_url;
    },
    addFormSubmit() {
      console.log(this.addForm);
      let _data = {
        id: this.addForm.id,
        category: this.addForm.category, //分类
        everyRePrice: this.addForm.everyRePrice, // 每人返还价格人民币
        inPrice: this.addForm.inPrice, //实际金额

        price: this.addForm.price, // 用户充值金额
        content: this.addForm.content,
        img: this.addForm.picUrl,
        bannerImg: JSON.stringify(this.addForm.piclist),
        remark: this.addForm.remark,

        title: this.addForm.title,
        totalNumber: this.addForm.totalNumber,
        number: this.addForm.number, // 每N次产生一个七益
        curNumber: this.addForm.curNumber
      };
      _data.status = this.addForm.status == true ? 1 : 0;
      console.log(_data);
      this.$http.post("/manage/seven/addEdit", _data).then(res => {
        if (res.data.status == 1) {
          this.addDialogVisible = false;
          this.getsevenList();
          this.$message({
            message: "添加成功",
            type: "success"
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    addRoot() {
      this.addDialogVisible = true;
    },
    // 每当要预览图片的时候，会触发这个函数
    handlePreview(result) {
      console.log(result);
      this.previewURL = result.url;
      console.log(this.previewURL);
      this.previewDialogVisible = true;
    },
    //单图预览
    dThandlePreview(result) {
      console.log(result);
      this.previewURL = result.url;
      console.log(this.previewURL);
      this.previewDialogVisible = true;
    },

    edithandleRemove(){
      this.editForm.img="";
    },

    // 每当要删除对应的图片，都会触发这个函数
    handleRemove(result) {
      // 根据要删除的图片的地址，找到 图片在 this.addForm.pics 数组中，
      // 所对应的 索引
      const index = this.addForm.piclist.findIndex(x => x === result.url);
      // 根据索引。把 表单中记录的图片信息对象，删除
      this.addForm.piclist.splice(index, 1);
      // console.log(this.addForm)
    },
    beforeUpload(file) {
      console.log(file);
      this.params.key = file.name;
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
    },
    edituploadSuccess(result){
      let picUrl = this.form.domain + result.key;
      this.editForm.img=picUrl;
    },
    // 每当图片上传成功，都会触发这个函数
    uploadSuccess(result) {
      // console.log(result)
      // 只要图片上传成功，都要 怼出这么一个对象：
      //  { pic: '图片的地址' }
      // 把怼出的对象，push 到this.addForm.pics 中
      let picUrl = this.form.domain + result.key;
      const obj = { bannerimg: picUrl };
      console.log(obj, "上传图片的地址");
      this.addForm.piclist.push(obj);
      // console.log(this.addForm)
    },
    editDtuploadSuccess(result){
      // console.log(result)
      // 只要图片上传成功，都要 怼出这么一个对象：
      //  { pic: '图片的地址' }
      // 把怼出的对象，push 到this.addForm.pics 中
      let picUrl = this.form.domain + result.key;
      const obj = { bannerimg: picUrl };
      console.log(obj, "上传图片的地址");
      this.editImgList.push(obj);
      // console.log(this.addForm)
    },
    editDthandleRemove(result){
      const index = this.editImgList.findIndex(x => x === result.url);
      // 根据索引。把 表单中记录的图片信息对象，删除
      this.editImgList.splice(index, 1);
    },

    // 每当要删除对应的图片，都会触发这个函数
    dThandleRemove(result) {
      // 根据要删除的图片的地址，找到 图片在 this.addForm.pics 数组中，
      // 所对应的 索引
      //const index = this.addForm.pics.findIndex(x => x.pic === result.response.data.tmp_path)
      // 根据索引。把 表单中记录的图片信息对象，删除
      this.addForm.picture = "";
      // console.log(this.addForm)
    },
    dTbeforeUpload(file) {
      console.log(file);
      this.params.key = file.name;
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
    },
    dTuploadSuccess(result) {
      console.log(result);
      // 只要图片上传成功，都要 怼出这么一个对象：
      //  { pic: '图片的地址' }
      // 把怼出的对象，push 到this.addForm.pics 中
      let picUrl = this.form.domain + result.key;
      this.addForm.picUrl = picUrl;
      // console.log(this.addForm)
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log(file);
      this.params.key = file.name;
      //   const isJPG = file.type === "image/png";
      //   const isLt2M = file.size / 1024 / 1024 < 2;

      //   if (!isJPG) {
      //     this.$message.error("上传头像图片只能是 JPG 格式!");
      //   }
      //   if (!isLt2M) {
      //     this.$message.error("上传头像图片大小不能超过 2MB!");
      //   }
      //   return isJPG && isLt2M;
    },
    getimgtu(img) {
      let array = [];
      JSON.parse(img).forEach(obj => {
        array.push(obj.bannerimg);
      });
      console.log(array);
      return array;
    },
    checkimg(img) {
      this.srcList = [];
      // var url = window.location.href;
      // console.log(url)

      console.log(img);
      this.srcList.push(img);
    },
    getsevenList() {
      let _data = {
        pageNo: 1,
        pageSize: 10,
        queryId: -1,
        queryString: "", // 名字
        queryType: 0 //类型
      };
      this.$http.post("/manage/seven/sevenList", _data).then(res => {
        // console.log(res);
        if (res.data.status == 1) {
          this.dataList = res.data.data.list;
          console.log(this.dataList);
        }
      });
    }
  }
};
</script>
<style lang="less">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
